package com.tianci.appstore.ui.gamezone;

import android.animation.Animator;
import android.animation.Animator.AnimatorListener;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;

import com.coocaa.app.gamecenter.pages.detail.DetailActivity;
import com.coocaa.x.app.framework.app.LiteAppApplication;
import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.framework.utils.PMUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litedownloader.data.DownloadExtra;
import com.coocaa.x.service.litedownloader.data.DownloadTask;
import com.coocaa.x.service.litedownloader.data.TaskInfo;
import com.coocaa.x.service.litepm.data.AppInfo;
import com.skyworth.framework.skysdk.ipc.SkyStartActivity;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreException;
import com.tianci.appstore.AppDetailActivity;
import com.tianci.appstore.R;
import com.tianci.appstore.dataprovider.AppDataProvider;
import com.tianci.appstore.ui.SkinManager;
import com.tianci.appstore.ui.data.SkyAppDetailData;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.loading.LoadingView;
import com.tianci.appstore.ui.util.UICommon;
import com.tianci.appstore.ui.widget.CatchImageView;
import com.tianci.appstore.ui.widget.TipToast;
import com.tianci.appstore.utils.AsyncTask;
import com.tianci.appstore.utils.SkyConstants;
import com.tianci.appstore.utils.SkyNetImageCache;
import com.tianci.appstore.utils.SkyNetImageCache.ImageLoadListener;
import com.tianci.appstore.utils.Tools;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GameZoneView extends FrameLayout implements ImageLoadListener {
    private Context mContext;

    private int startSpacingX = SkyConstants.Div(103);    // 第一个游戏海报的左边缘距屏幕左边界的距离
    private int startSpacingY = SkyConstants.Div(48);
    private int itemSpacing = SkyConstants.Div(103);
    private int sizeDelta = SkyConstants.Div(32);   // 选中发光图的边距

    private int focusIndex;
    private int currentPosX;
    private int firstVisibleItem;
    private final int visibleCount = 6;

    private FrameLayout bottomLayout;
    private ImageView focusImage;
    private ImageView posterImage;
    private Button oneKeySetupBtn;
    private List<GameItemView> viewList;
    private GameItemView leftHideItemView;
    private GameItemView rightHideItemView;
    private String bgPosterUrl;
    private List<SkyListAppData> dataList;
    private boolean animRunning = false;
    private boolean isOneKeySetup = false;
    private boolean oneKeyBtnHasFocus = false;
    private int moveFocusDuration = 100;
    private int moveViewDuration = 100;

    private LoadingView loadingView;
    private TextView tipText;
    private boolean isGame = false;

    private static final int UPDATE_POSTER = 1;
    private static final int SHOW_TOAST = 2;

    public GameZoneView(Context context) {
        super(context);
        this.mContext = context;
        // TODO Auto-generated constructor stub
//        initDownTask();
        posterImage = new CatchImageView(context);
        posterImage.setScaleType(ScaleType.FIT_XY);
        this.addView(posterImage, new LayoutParams(
                LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        loadingView = new LoadingView(context);
        this.addView(loadingView, new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, Gravity.CENTER));

        tipText = UICommon.newTextView(context, UICommon.tipTextSize, R.color.tipColor);
        this.addView(tipText, new LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, Gravity.CENTER));
        tipText.setVisibility(View.INVISIBLE);

        bottomLayout = new FrameLayout(mContext);
        focusImage = new ImageView(mContext);
        focusImage.setBackgroundDrawable(SkinManager.getResDrawable(R.drawable.pic_focus));

        this.addView(bottomLayout, new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT, Gravity.BOTTOM));
        SkinManager.setBackground(bottomLayout, R.drawable.game_zone_shadow);
        bottomLayout.setPadding(0, 0, 0, SkyConstants.Div(45));
//        this.addView(focusImage, new LayoutParams(GameItemView.POSTER_WIDTH
//                + 2 * sizeDelta, GameItemView.POSTER_HEIGHT + 2 * sizeDelta));
        focusImage.setVisibility(View.INVISIBLE);

        loadingView.startLoading();
        loadingView.setVisibility(View.VISIBLE);
    }

    public void setIsGame(boolean isGame){
        this.isGame = isGame;
        LogUtils.d("isgame","isgame is " + isGame);
    }

    public void addOneKeySetupBtn() {
        LayoutParams oneKeySetupParams =  new LayoutParams( SkyConstants.Div(320), SkyConstants.Div(125));
        oneKeySetupParams.topMargin = SkyConstants.Div(330);
        oneKeySetupParams.leftMargin = SkyConstants.Div(1497);
        oneKeySetupBtn = new Button(mContext);
        oneKeySetupBtn.setTextColor(getResources().getColor(R.color.titleColor));
        oneKeySetupBtn.setText("一键安装");
        oneKeySetupBtn.setTextSize(SkyConstants.Dpi(40));
        oneKeySetupBtn.setBackgroundResource(R.drawable.onkeysetupbg);
        oneKeySetupBtn.setClickable(false);
        this.addView(oneKeySetupBtn, oneKeySetupParams);
        oneKeyBtnHasFocus = true;
    }

    public void update(String bgUrl, List<SkyListAppData> dataList, boolean oneKeySetup) {
        if (dataList == null || dataList.size() == 0) {
            loadingView.setVisibility(View.INVISIBLE);
            tipText.setText(R.string.game_item_empty);
            tipText.setVisibility(View.VISIBLE);
            return;
        }

        LogUtils.i("zone", "oneKeySetup: "+oneKeySetup);
        isOneKeySetup = oneKeySetup;

        // 下载图片
        if (bgUrl != null && bgUrl.length() > 0) {
            this.bgPosterUrl = bgUrl;
            SkyNetImageCache.getSkyNetImageCache().downloadUrl("", bgUrl, this, 0, 0);
        }

        tipText.setVisibility(View.INVISIBLE);
        this.dataList = dataList;
        if (viewList == null)
            viewList = new ArrayList<GameItemView>();
        for (int i = 0; i < dataList.size(); i++) {
            if (i >= visibleCount)
                break;
            SkyListAppData data = dataList.get(i);
            GameItemView itemView;
            if (i < viewList.size())
                itemView = viewList.get(i);
            else {
                itemView = new GameItemView(mContext);
                viewList.add(itemView);
                LayoutParams params = new LayoutParams(GameItemView.POSTER_WIDTH,
                        LayoutParams.WRAP_CONTENT);
                params.leftMargin = computeChildPosX(i);
                params.topMargin = startSpacingY;
                bottomLayout.addView(itemView, params);
            }
            itemView.setId(i);
            itemView.update(data);
        }
        while (viewList.size() > dataList.size()) {
            this.removeView(viewList.get(viewList.size() - 1));
            viewList.remove(viewList.size() - 1);
        }

        if (dataList.size() > visibleCount) {
            if (leftHideItemView == null) {
                leftHideItemView = new GameItemView(mContext);
                LayoutParams params = new LayoutParams(GameItemView.POSTER_WIDTH,
                        LayoutParams.WRAP_CONTENT);
                params.leftMargin = -GameItemView.POSTER_WIDTH - sizeDelta;
                params.topMargin = startSpacingY;
                bottomLayout.addView(leftHideItemView, params);
                leftHideItemView.animate().x(computeChildPosX(visibleCount))
                        .setDuration(0).setListener(null);
                leftHideItemView.setVisibility(View.INVISIBLE);
            }
            if (rightHideItemView == null) {
                rightHideItemView = new GameItemView(mContext);
                LayoutParams params = new LayoutParams(GameItemView.POSTER_WIDTH,
                        LayoutParams.WRAP_CONTENT);
                params.leftMargin = computeChildPosX(visibleCount) + sizeDelta;
                params.topMargin = startSpacingY;
                bottomLayout.addView(rightHideItemView, params);
                rightHideItemView.animate().x(computeChildPosX(visibleCount))
                        .setDuration(0).setListener(animListener);
                rightHideItemView.setVisibility(View.INVISIBLE);
            }
        }

        focusIndex = 0;
        firstVisibleItem = 0;
        FrameLayout.LayoutParams focusParams;

        if(isOneKeySetup) {
            oneKeyBtnHasFocus = true;
            focusParams = new LayoutParams(SkyConstants.Div(320) + 2 * sizeDelta,
                    SkyConstants.Div(125) + 2 * sizeDelta);
            this.addView(focusImage, focusParams);
            focusImage.animate().x(SkyConstants.Div(1497) - sizeDelta)
                    .y(SkyConstants.Div(330) - sizeDelta).setDuration(moveFocusDuration).start();
            currentPosX = computeChildPosX(focusIndex - firstVisibleItem);
            addOneKeySetupBtn();
        } else {
            oneKeyBtnHasFocus = false;
            focusParams = new LayoutParams(GameItemView.POSTER_WIDTH
                + 2 * sizeDelta, GameItemView.POSTER_HEIGHT + 2 * sizeDelta);
            focusParams.leftMargin = computeChildPosX(focusIndex - firstVisibleItem) - sizeDelta;
            focusParams.topMargin = startSpacingY - sizeDelta;
            bottomLayout.addView(focusImage, focusParams);
            viewList.get(focusIndex - firstVisibleItem).setSelected(true);
        }

        focusImage.setVisibility(View.VISIBLE);

    }

    public void updateAppStatus(String pkgName, SkyAppDetailData.AppStatus status) {
        int count = bottomLayout.getChildCount();
        for (int i = 0; i < count; i++) {
            View child = (View) bottomLayout.getChildAt(i);
            if (child instanceof GameItemView && ((GameItemView) child).data != null) {
                String pkg = ((GameItemView) child).data.getPkgName();
                if (pkg != null && pkg.equals(pkgName)) {
                    ((GameItemView) child).updateAppStatus(status);
                    if(status == SkyAppDetailData.AppStatus.INSTALLED
                            || status == SkyAppDetailData.AppStatus.NOT_DOWNLOADED) {
                        if(taskMap.containsKey(getDownurl(((GameItemView) child).data.getId(), "")))
                            taskMap.remove(getDownurl(((GameItemView) child).data.getId(), ""));
                    }
                }
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        LogUtils.d("zone", "onKeyDown: "+keyCode);
        if (processKeyDown(keyCode, event))
            return true;
        return super.onKeyDown(keyCode, event);
    }

    public boolean processKeyDown(int keyCode, KeyEvent event) {
        if (dataList == null)
            return false;
        switch (keyCode) {
            case KeyEvent.KEYCODE_DPAD_LEFT:
            case KeyEvent.KEYCODE_DPAD_RIGHT:
            case KeyEvent.KEYCODE_DPAD_UP:
            case KeyEvent.KEYCODE_DPAD_DOWN:
                changeFocus(keyCode);
                return true;
            case KeyEvent.KEYCODE_DPAD_CENTER:
            case KeyEvent.KEYCODE_ENTER:
                LogUtils.d("zone", "enterDetailPage");
                enterDetailPage();
                return true;
        }
        return false;
    }

    private HashMap<String, DownloadTask> taskMap = new HashMap<String, DownloadTask>();
    private Map<String, String> urlMap = new HashMap<String, String>();
//    private void initDownTask() {
//        AsyncTask.runOnThread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    List<DownloadTask> list = XServiceManager.getDownloaderService()
//                            .getTaskList();
//                    synchronized (taskMap) {
//                        taskMap.clear();
//                        for (DownloadTask task : list)
//                            taskMap.put(task.url, task);
//                    }
//                } catch (RemoteException e) {
//                    e.printStackTrace();
//                }
//            }
//        });
//    }

    private void onKeyDownload() {
        AsyncTask.runOnThread(new Runnable() {
            @Override
            public void run() {
                int installSize = 0;
                int unInstallSize = 0;
                List<DownloadTask> list = null;
                try {
                    list = XServiceManager.getDownloaderService()
                            .getTaskList();
                    synchronized (taskMap) {
                        taskMap.clear();
                        for (DownloadTask task : list)
                            taskMap.put(task.url, task);
                    }
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

                for(SkyListAppData appData: dataList) {
                    SkyAppDetailData.AppStatus status = SkyAppDetailData.AppStatus.NOT_DOWNLOADED;
                    status = getAppStatus(appData.getPkgName(), "", list);

                    if(status == SkyAppDetailData.AppStatus.INSTALLED) {
                        installSize++;
                        continue;
                    }
                    if(status == SkyAppDetailData.AppStatus.NOT_DOWNLOADED) {
                        downloadApp(appData);
                        unInstallSize++;
                    }

                    if(status == SkyAppDetailData.AppStatus.DOWNLOAD_PAUSED) {
                        downloadContinue(appData);
                        unInstallSize++;
                    }
                }

                LogUtils.d("intent", "21026 taskMap.size = "+taskMap.size());
                if(installSize == dataList.size()) {
                    Message message = new Message();
                    message.what = SHOW_TOAST;
                    message.obj = mContext.getString(R.string.toast_onekey_setup_allinstalled);
                    mainHandler.sendMessage(message);
                    return;
                }

                if(unInstallSize == 0) {
                    Message message = new Message();
                    message.what = SHOW_TOAST;
                    message.obj = mContext.getString(R.string.toast_onekey_setup_downloading);
                    mainHandler.sendMessage(message);
                } else {
                    Message message = new Message();
                    message.what = SHOW_TOAST;
                    message.obj = mContext.getString(R.string.toast_start_onekey_setup);
                    mainHandler.sendMessage(message);
                }
            }
        });
    }

    private void downloadContinue(SkyListAppData appData) {
        try {
            DownloadTask task = null;
            String download_url = getDownurl(appData.getId(), "");
            synchronized (taskMap) {
                task = taskMap.get(download_url);
            }
            if (task != null) {
                if (task.url == null) {
                    while (task.url == null)
                        task.url = download_url;
                }
                XServiceManager.getDownloaderService().start(task);
                // AppDataProvider.getInstance().getServiceData().start(task);
                DownloadExtra extra = DownloadExtra.parseJObject(task.extra,
                        DownloadExtra.class);
            }
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void downloadApp(SkyListAppData appData){
        if (!LiteAppApplication.checkNetworkConnection(TipToast.showNetIsNotConnectedToastRunnable))
            return;
        String download_url = getDownurl(appData.getId(), "");
        LogUtils.d("download_url:" + download_url);
        if (download_url != null) {
            String download_path = AppDataProvider.getInstance().getDownloadPath();
            try {
                DownloadTask task = taskMap.get(download_url);

                if (task == null) {
                    DownloadExtra extra = new DownloadExtra(appData.getId(),
                            appData.getPkgName(), appData.getIconUrl(),
                            appData.getTitle());
                    task = new DownloadTask(download_url);
                    task.title = appData.getTitle();
                    task.url = download_url;
                    task.filename = appData.getPkgName() + ".apk";
                    task.extra = extra.toString();
                    synchronized (taskMap) {
                        taskMap.put(download_url, task);
                    }
                }
                XServiceManager.getDownloaderService().add(task);
                XServiceManager.getDownloaderService().start(task);
                task = XServiceManager.getDownloaderService().refresh(task);
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private String getDownurl(String appid, String usercount) {
        try {
            String downurl = null;
            synchronized (urlMap) {
                downurl = urlMap.get(appid);
            }
            if (downurl == null) {
                downurl = CoocaaApplication.getCoocaaWebService().getAppStoreService().getDownAddress(
                        Integer.valueOf(appid), usercount);
                urlMap.put(appid, downurl);
            }
            System.out.println("download url:" + downurl);
            return downurl;
        } catch (AppStoreException e) {
            LogAPIForAppStore.reportInterfaceError("获取应用下载地址接口",
                    Android.throwable2String(e));
            System.out.println("错误原因：" + e.getErrormsg());
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    private SkyAppDetailData.AppStatus getAppStatus(String pkg, String versionCode, List<DownloadTask> list) {

        if (pkg.equals("com.developer.fans") && Android.isPackageInstalled(mContext, pkg)) {
            return SkyAppDetailData.AppStatus.INSTALLED;
        }

        String status = SkyAppDetailData.AppStatus.NOT_DOWNLOADED.toString();
        try {
            switch (XServiceManager.getLitePMService().getAppInstallState(pkg)) {
                case PMUtils.INSTALL_STATE_INSTALLED:
                    status = SkyAppDetailData.AppStatus.INSTALLED.toString();
                    break;
                case PMUtils.INSTALL_STATE_INSTALLING:
                    status = SkyAppDetailData.AppStatus.INSTALLING.toString();
                    break;
                default:
                    break;
            }
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        switch (SkyAppDetailData.AppStatus.valueOf(status)) {
            case INSTALLING:
            case UNINSTALLING:
                return SkyAppDetailData.AppStatus.valueOf(status);
            default:
                break;
        }

        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                DownloadExtra extra = DownloadExtra.parseJObject(list.get(i).extra,
                        DownloadExtra.class);
                if (extra.pkgname.equals(pkg)) {
                    // RemoteDownloaderTask task = list.get(i);
                    TaskInfo.TASK_STATE state = list.get(i).info.state;
                    LogUtils.d("status", extra.title + " TASK_STATE:" + state);
                    switch (state) {
                        case READY:
                            return SkyAppDetailData.AppStatus.WAITING;
                        case PROCESSING:
                            return SkyAppDetailData.AppStatus.DOWNLOADING;
                        case STOPED:
                            return SkyAppDetailData.AppStatus.DOWNLOAD_PAUSED;
                        case FINISH:
                            return SkyAppDetailData.AppStatus.DOWNLOADED;
                        default:
                            return SkyAppDetailData.AppStatus.WAITING;
                    }
                }
            }
        }
        AppInfo localInfo = null;
        try {
            localInfo = XServiceManager.getLitePMService().getAppInfo(pkg);
        } catch (RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (localInfo != null && localInfo.versionCode > 0) {
            long newVersion = Tools.getVersionFromString(versionCode);
            long oldVersion = localInfo.versionCode;
            // long oldVersion = Tools.getVersionFromString(localInfo.versionName);
            LogUtils.d("liqiwen", "getAppStatus----newVersion---oldVersion--" + newVersion + "  "
                    + oldVersion);
            if (newVersion > oldVersion) {
                return SkyAppDetailData.AppStatus.HAS_NEW_VERSION;
            } else {
                return SkyAppDetailData.AppStatus.INSTALLED;
            }
        }
        return SkyAppDetailData.AppStatus.NOT_DOWNLOADED;
    }

    private void enterDetailPage() {
        if(oneKeyBtnHasFocus && isOneKeySetup) {
            //一键安装
            LogUtils.d("intent", "taskMap.size="+taskMap.size());
            onKeyDownload();
            return;
        }

        if (dataList == null || focusIndex < 0 || focusIndex >= dataList.size()) {
            LogUtils.d("game_zone", "Game zone item clicked, but data = null !!!!!!!!!!!!");
            return;
        }

        Intent intent = null;
        if (!isGame){
            String strId = this.dataList.get(focusIndex).getId();
            if (strId == null || strId.trim().length() == 0)
                return;
            intent = new Intent(mContext, AppDetailActivity.class);
            intent.putExtra("id", strId);
        }else{
            intent = new Intent("com.coocaa.gamecenter.detail");
            int appid = -1;
            try {
                appid = Integer.valueOf(this.dataList.get(focusIndex).getId());
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            intent.putExtra(DetailActivity.INTENT_APPID_KEY, appid);
            intent.putExtra(DetailActivity.INTENT_PACKAGENAME_KEY, this.dataList.get(focusIndex).getPkgName());
        }

//        mContext.startActivity(intent);
        HashMap<String,String> map = new HashMap<String,String>();
        SkyStartActivity.startActivity(mContext, mContext.getClass().getName(), intent, map, false);
    }

    /*
        direction:
     */
    private void changeFocus(int keyCode) {
        if (animRunning)
            return;
        if(oneKeyBtnHasFocus && keyCode != KeyEvent.KEYCODE_DPAD_DOWN) {
            return;
        }

        if(isOneKeySetup == false
                && (keyCode == KeyEvent.KEYCODE_DPAD_DOWN || keyCode == KeyEvent.KEYCODE_DPAD_UP)) {
            return;
        }

        if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
            if (focusIndex > 0) {
                if (focusIndex > firstVisibleItem) {
                    viewList.get(focusIndex - firstVisibleItem).setSelected(false);
                    focusIndex--;
                    viewList.get(focusIndex - firstVisibleItem).setSelected(true);
                    currentPosX = computeChildPosX(focusIndex - firstVisibleItem);
                    focusImage.animate().x(currentPosX - sizeDelta)
                            .setDuration(moveFocusDuration).start();
                } else {
                    SkyListAppData data = dataList.get(focusIndex - 1);
                    leftHideItemView.setId(focusIndex - 1);
                    leftHideItemView.update(data);
                    leftHideItemView.setVisibility(View.VISIBLE);
                    for (int i = 0; i < visibleCount; i++) {
                        GameItemView itemView = viewList.get(i);
                        itemView.animate().x(computeChildPosX(i + 1))
                                .setDuration(moveViewDuration).setListener(null);
                    }
                    leftHideItemView.animate().x(computeChildPosX(0)).
                            setDuration(moveViewDuration + 10).setListener(leftAnimListener);
                }
            } else {   // hit left wall

            }
        } else if(keyCode == KeyEvent.KEYCODE_DPAD_RIGHT){
            if (focusIndex < dataList.size() - 1) {
                if (focusIndex < firstVisibleItem + visibleCount - 1) {
                    viewList.get(focusIndex - firstVisibleItem).setSelected(false);
                    focusIndex++;
                    viewList.get(focusIndex - firstVisibleItem).setSelected(true);

                    currentPosX = computeChildPosX(focusIndex - firstVisibleItem);
                    focusImage.animate().x(currentPosX - sizeDelta)
                            .setDuration(moveFocusDuration).start();
                } else {
                    SkyListAppData data = dataList.get(focusIndex + 1);
                    rightHideItemView.setId(focusIndex + 1);
                    rightHideItemView.update(data);
                    rightHideItemView.setVisibility(View.VISIBLE);
                    for (int i = 0; i < visibleCount; i++) {
                        GameItemView itemView = viewList.get(i);
                        itemView.animate().x(computeChildPosX(i - 1))
                                .setDuration(moveViewDuration).setListener(null);
                    }
                    rightHideItemView.animate().x(computeChildPosX(visibleCount - 1))
                            .setDuration(moveViewDuration + 10).setListener(rightAnimListener);
                }
            }
        } else if(keyCode == KeyEvent.KEYCODE_DPAD_UP){
            oneKeyBtnHasFocus = true;
            FrameLayout.LayoutParams focusParams = (FrameLayout.LayoutParams)
                    focusImage.getLayoutParams();
            focusParams.width = SkyConstants.Div(320) + 2 * sizeDelta;
            focusParams.height = SkyConstants.Div(125) + 2 * sizeDelta;
            LogUtils.d("zone", "leftmargin: "+(SkyConstants.Div(1497) - sizeDelta));
            focusImage.setLayoutParams(focusParams);
            focusImage.animate().x(SkyConstants.Div(1497) - sizeDelta)
                    .y(SkyConstants.Div(330) - sizeDelta).setDuration(moveFocusDuration).start();
        } else if(keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
            oneKeyBtnHasFocus = false;
            FrameLayout.LayoutParams focusParams = (FrameLayout.LayoutParams)
                    focusImage.getLayoutParams();
            focusParams.width = GameItemView.POSTER_WIDTH + 2 * sizeDelta;
            focusParams.height = GameItemView.POSTER_HEIGHT + 2 * sizeDelta;
            LogUtils.d("zone", "currentPosX: "+currentPosX);
            focusImage.setLayoutParams(focusParams);
            focusImage.animate().x(currentPosX - sizeDelta)
                    .y( startSpacingY - sizeDelta + SkyConstants.Div(543)).setDuration(moveFocusDuration).start();
        }
    }

    private AnimatorListener leftAnimListener = new AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {
            // TODO Auto-generated method stub
            animRunning = true;
        }

        @Override
        public void onAnimationRepeat(Animator animation) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onAnimationEnd(Animator animation) {
            // TODO Auto-generated method stub
            viewList.get(0).setSelected(false);
            GameItemView itemView = viewList.get(visibleCount - 1);
            viewList.remove(visibleCount - 1);
            viewList.add(0, leftHideItemView);
            leftHideItemView = itemView;

            focusIndex--;
            firstVisibleItem--;
            viewList.get(0).setSelected(true);
            leftHideItemView.animate().x(computeChildPosX(-1))
                    .setDuration(0).setListener(animListener);
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            // TODO Auto-generated method stub
            animRunning = false;
        }
    };

    private AnimatorListener rightAnimListener = new AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {
            // TODO Auto-generated method stub
            animRunning = true;
        }

        @Override
        public void onAnimationRepeat(Animator animation) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onAnimationEnd(Animator animation) {
            // TODO Auto-generated method stub
            viewList.get(visibleCount - 1).setSelected(false);
            GameItemView itemView = viewList.get(0);
            viewList.remove(0);
            viewList.add(rightHideItemView);
            rightHideItemView = itemView;

            focusIndex++;
            firstVisibleItem++;
            viewList.get(visibleCount - 1).setSelected(true);

            rightHideItemView.animate().x(computeChildPosX(visibleCount))
                    .setDuration(0).setListener(animListener);
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            // TODO Auto-generated method stub
            animRunning = false;
        }
    };

    private AnimatorListener animListener = new AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onAnimationRepeat(Animator animation) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onAnimationEnd(Animator animation) {
            // TODO Auto-generated method stub
            animRunning = false;
        }

        @Override
        public void onAnimationCancel(Animator animation) {
            // TODO Auto-generated method stub
            animRunning = false;
        }
    };

    private int computeChildPosX(int childPos) {
        int posX = startSpacingX + childPos * (itemSpacing + GameItemView.POSTER_WIDTH);
        return posX;
    }

    @Override
    public void loadFinished(String url, Bitmap result) {
        // TODO Auto-generated method stub
        if (url == null || url.equals("") || !url.equals(bgPosterUrl))
            return;
        LogUtils.d("zone", "ZoneView load big poster finished, url = " + url);
        Message msg = mainHandler.obtainMessage(UPDATE_POSTER);
        msg.obj = result;
        mainHandler.sendMessage(msg);
    }

    private Handler mainHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            switch (msg.what) {
                case UPDATE_POSTER:
                    loadingView.stopLoading();
                    loadingView.setVisibility(View.INVISIBLE);
                    posterImage.setImageBitmap(((Bitmap) msg.obj));
                    break;
                case SHOW_TOAST:
                    LogUtils.i("zone", "SHOW_TOAST");
                    String toastMsg = (String)msg.obj;
                    TipToast.getInstance(mContext).showTipToast(toastMsg);
                    break;
            }
            super.handleMessage(msg);
        }
    };
}
